package com.papers.juan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.domain.dto.RoleDTO;
import com.papers.common.core.domain.entity.SysDictData;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.exception.ServiceException;
import com.papers.common.helper.LoginHelper;
import com.papers.common.utils.BeanCopyUtils;
import com.papers.common.utils.StringUtils;
import com.papers.juan.domain.TJuanQuestion;
import com.papers.juan.domain.TJuanQuestionRepos;
import com.papers.juan.domain.bo.TJuanQuestionBo;
import com.papers.juan.domain.dto.InsertQuestion;
import com.papers.juan.domain.dto.JuanQuestionDto;
import com.papers.juan.domain.vo.KnowledgeReturnVO;
import com.papers.juan.domain.vo.QuestionVO;
import com.papers.juan.domain.vo.ReposImportVO;
import com.papers.juan.domain.vo.StatisticsByTypeVO;
import com.papers.juan.domain.vo.TJuanQuestionVo;
import com.papers.juan.mapper.TJuanQuestionMapper;
import com.papers.juan.mapper.TJuanQuestionReposMapper;
import com.papers.juan.mapper.TJuanReposRelatedMapper;
import com.papers.juan.service.ITJuanQuestionService;
import com.papers.juan.utils.Node;
import com.papers.juan.utils.TreeUtils;
import com.papers.system.domain.TJuanChapter;
import com.papers.system.domain.TJuanCourse;
import com.papers.system.domain.TJuanKnowledge;
import com.papers.system.domain.vo.TJuanLeftTreeVo;
import com.papers.system.mapper.TJuanChapterMapper;
import com.papers.system.mapper.TJuanCourseMapper;
import com.papers.system.mapper.TJuanKnowledgeMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 题目Service业务层处理
 *
 * @author papers
 * @date 2022-10-08
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class TJuanQuestionServiceImpl implements ITJuanQuestionService {

    private final TJuanQuestionMapper baseMapper;
    private final TJuanQuestionReposMapper tJuanQuestionReposMapper;
    private final TJuanKnowledgeMapper tJuanKnowledgeMapper;
    private final TJuanReposRelatedMapper tJuanReposRelatedMapper;
    private final TJuanChapterMapper tJuanChapterMapper;
    private final TJuanCourseMapper tJuanCourseMapper;

    /**
     * 查询题目
     */
    @Override
    public TJuanQuestionVo queryById(String questionId) {
        return baseMapper.selectVoById(questionId);
    }

    /**
     * 查询题目列表
     */
    @Override
    public TableDataInfo<TJuanQuestionVo> queryPageList(TJuanQuestionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TJuanQuestion> lqw = buildQueryWrapper(bo);
        Page<TJuanQuestionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询题目列表
     */
    @Override
    public List<TJuanQuestionVo> queryList(JuanQuestionDto bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<TJuanQuestion> lqw = buildQueryWrapper(bo);
//        List<TJuanQuestionVo> voList = baseMapper.selectVoList(lqw);
        if (StringUtils.isBlank(bo.getCourseId())) {
            throw new ServiceException("请选择一个题库");
        }
        IPage<TJuanQuestionVo> page = pageQuery.build();
        page = baseMapper.getQuestionList(page, bo);
        List<TJuanQuestionVo> records = page.getRecords();
        Map<String, String> reposCollect = tJuanQuestionReposMapper.selectList().stream().collect(Collectors.toMap(TJuanQuestionRepos::getReposId, TJuanQuestionRepos::getReposCode));
        Map<String, String> knowledgeCollect = tJuanKnowledgeMapper.selectList().stream().collect(Collectors.toMap(TJuanKnowledge::getKnowledgeId, TJuanKnowledge::getKnowledgeCode));
        String reposId = bo.getReposId();
        records.stream().forEach(item -> {
            item.setReposCode(reposCollect.get(reposId));
            item.setKnowledgeCode(knowledgeCollect.get(item.getKnowledgeId()));
        });
        return records;
    }

    private LambdaQueryWrapper<TJuanQuestion> buildQueryWrapper(TJuanQuestionBo bo) {
//        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TJuanQuestion> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCourseId()), TJuanQuestion::getCourseId, bo.getCourseId());
//        lqw.eq(StringUtils.isNotBlank(bo.getChapterId()), TJuanQuestion::getChapterId, bo.getChapterId());
        lqw.eq(StringUtils.isNotBlank(bo.getKnowledgeId()), TJuanQuestion::getKnowledgeId, bo.getKnowledgeId());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionCode()), TJuanQuestion::getQuestionCode, bo.getQuestionCode());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionType()), TJuanQuestion::getQuestionType, bo.getQuestionType());
        lqw.eq(bo.getQuestionDifficult() != null, TJuanQuestion::getQuestionDifficult, bo.getQuestionDifficult());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionEasy()), TJuanQuestion::getQuestionEasy, bo.getQuestionEasy());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionMajor()), TJuanQuestion::getQuestionMajor, bo.getQuestionMajor());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionGrade()), TJuanQuestion::getQuestionGrade, bo.getQuestionGrade());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionSubject()), TJuanQuestion::getQuestionSubject, bo.getQuestionSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getQuestionContent()), TJuanQuestion::getQuestionContent, bo.getQuestionContent());
        lqw.eq(StringUtils.isNotBlank(bo.getCreatedBy()), TJuanQuestion::getCreatedBy, bo.getCreatedBy());
        lqw.eq(bo.getCreatedTime() != null, TJuanQuestion::getCreatedTime, bo.getCreatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdatedBy()), TJuanQuestion::getUpdatedBy, bo.getUpdatedBy());
        lqw.eq(bo.getUpdatedTime() != null, TJuanQuestion::getUpdatedTime, bo.getUpdatedTime());
        return lqw;
    }

    /**
     * 新增题目
     */
    @Override
    public Boolean insertByBo(TJuanQuestionBo bo) {
        TJuanQuestion add = BeanUtil.toBean(bo, TJuanQuestion.class);
        add.setCreatedTime(new Date());
        Long userId = LoginHelper.getUserId();
        add.setCreatedBy(userId + "");
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setQuestionId(add.getQuestionId());
        }
        return flag;
    }

    /**
     * 修改题目
     */
    @Override
    public Boolean updateByBo(TJuanQuestionBo bo) {
        TJuanQuestion update = BeanUtil.toBean(bo, TJuanQuestion.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TJuanQuestion entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除题目
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R getQuestionList(JuanQuestionDto dto, PageQuery pageQuery) {
        if (StringUtils.isNotBlank(dto.getKnowledgeId())) {
            IPage<TJuanQuestionVo> page = pageQuery.build();
            if ("course".equals(dto.getTreeType())) {
                Page<TJuanQuestion> pages = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
                LambdaQueryWrapper<TJuanQuestion> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TJuanQuestion::getCourseId, dto.getKnowledgeId()).orderByAsc(TJuanQuestion::getQuestionCode);
                queryWrapper.eq(dto.getQuestionType() !=null,TJuanQuestion::getQuestionType,dto.getQuestionType());
                queryWrapper.eq(dto.getQuestionEasy() !=null,TJuanQuestion::getQuestionEasy,dto.getQuestionEasy());
                queryWrapper.eq(dto.getQuestionGrade() !=null,TJuanQuestion::getQuestionGrade,dto.getQuestionGrade());
//                List<TJuanQuestionVo> tJuanQuestions = baseMapper.selectVoList(queryWrapper);
                pages = baseMapper.selectPage(pages, queryWrapper);
                return R.ok(TableDataInfo.build(pages));
//                page = page.setRecords(tJuanQuestions);
            } else if ("knowledge".equals(dto.getTreeType())) {
                page = baseMapper.getQuestionList(page, dto);
            }
            log.info("数据：" + page);
            return R.ok(TableDataInfo.build(page));
        }
        return R.fail("请选择一个题库");
    }

    @Override
    public R getQuestionByIds(String ids) {
        List<TJuanQuestionVo> list = baseMapper.selectVoBatchIds(Arrays.asList(ids.split(",")));
        return R.ok(list);
    }

    @Override
    public R getChapterTreeByQuestion(String courseId) {
        if (StringUtils.isNotBlank(courseId)) {
            List<Node> list = baseMapper.getChapterTreeByQuestion(courseId);
            List<Node> treeList = TreeUtils.getTree(list);
            return R.ok(treeList);
        }
        return R.fail("请选择一个题库");
    }

    @Override
    public R getKnowledgeTreeByQuestion(String courseId) {
        //courseId现在传的是部门id
        //查看本人的角色
        List<RoleDTO> roles = LoginHelper.getRoles();
        //如果角色有且只有一个教员，则他只能看到他自己创建的题库
        String userName = null;
        if (roles.size() == 1) {
            if ("教员".equals(roles.get(0).getRoleName())) {
                userName = LoginHelper.getUsername();
            }
        }
        List<TJuanLeftTreeVo> courseTreeList = tJuanCourseMapper.getLeftTree(courseId, userName);
        //所有题库
        List<Node> allCource = new ArrayList<>();
        for (TJuanLeftTreeVo tJuanCourse : courseTreeList) {
            Node node = new Node();
            node.setid(tJuanCourse.getId());
            node.setNodeName(tJuanCourse.getTreeName());
            node.setTreeType("course");
            //查询该课程下所有的知识点
            List<Node> list = baseMapper.getKnowledgeTreeByQuestion(tJuanCourse.getId());
            List<Node> treeList = TreeUtils.getTree(list);
            node.setchildren(treeList);
            allCource.add(node);
        }
        return R.ok(allCource);
    }

    @Override
    public R getKnowledgeTreeByQuestion1(String courseId) {
        //查询该课程下所有的知识点
        List<Node> list = baseMapper.getKnowledgeTreeByQuestion(courseId);
        List<Node> treeList = TreeUtils.getTree(list);
        return R.ok(treeList);
    }

    @Override
    public R getQuestionListNew(JuanQuestionDto dto, PageQuery pageQuery) {
        if (StringUtils.isNotBlank(dto.getReposId())) {
            IPage<TJuanQuestionVo> page = pageQuery.build();
            page = baseMapper.getQuestionList(page, dto);
            log.info("数据：" + page);
            return R.ok(TableDataInfo.build(page));
        }
        return R.fail("请选择一个题库");
    }

    @Override
    public List<TJuanQuestionVo> selectQuestionList(JuanQuestionDto bo) {
        return baseMapper.selectQuestionList(bo);
    }
//    @Override
//    public R importQuestions(MultipartFile file) {
//        if (null == file) {
//            return R.fail("请选择一个文件");
//        }
//        try {
//            ExcelResult<TJuanQuestionVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TJuanQuestionVo.class, new TJunQuestionListener());
//
//        } catch (Exception e) {
//            log.error("导入题目异常", e);
//            e.printStackTrace();
//            return R.fail("系统异常请联系管理员");
//        }
//        return null;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcell(List<TJuanQuestionVo> voList, String tk) {
        List<TJuanQuestion> questionList = baseMapper.selectList();
        List<TJuanKnowledge> klList = tJuanKnowledgeMapper.selectByCourseId(tk);
        Map<String, TJuanKnowledge> codecollect = klList.stream().collect(Collectors.toMap(TJuanKnowledge::getKnowledgeCode, p -> p));
        Map<String, TJuanKnowledge> idcollect = klList.stream().collect(Collectors.toMap(TJuanKnowledge::getKnowledgeId, p -> p));
//        tJuanChapterMapper.selectList().stream().collect(Collectors.toMap(TJuanChapter::getKnowledgeCode, TJuanKnowledge::getKnowledgeId, (v1, v2) -> v1));
        List<TJuanQuestion> result = new ArrayList<>();
        for (TJuanQuestionVo item : voList) {
            TJuanQuestion tJuanQuestion = new TJuanQuestion();
            BeanCopyUtils.copy(item, tJuanQuestion);
            if (null == item.getKnowledgeCode()) {
                TJuanKnowledge tJuanKnowledge1 = idcollect.get(item.getKnowledgeId());
                if (null == tJuanKnowledge1) {
                    continue;
                }
                tJuanQuestion.setChapterId(tJuanKnowledge1.getChapterId());
            } else {
                TJuanKnowledge tJuanKnowledge = codecollect.get(item.getKnowledgeCode());
                if (null == tJuanKnowledge) {
                    continue;
                }
                tJuanQuestion.setKnowledgeId(tJuanKnowledge.getKnowledgeId());
                tJuanQuestion.setChapterId(tJuanKnowledge.getChapterId());
            }
            result.add(tJuanQuestion);
        }

        Map<String, List<TJuanQuestion>> listMap = result.stream().collect(Collectors.groupingBy(TJuanQuestion::getKnowledgeId));
        for (String key : listMap.keySet()) {
            //生成编码
            LambdaQueryWrapper<TJuanQuestion> questionWrapper = new LambdaQueryWrapper<>();
            questionWrapper.eq(TJuanQuestion::getKnowledgeId, key)
                    .orderByDesc(TJuanQuestion::getQuestionCode)
                    .last("LIMIT 1");
            TJuanQuestion questionMax = baseMapper.selectOne(questionWrapper);
            TJuanKnowledge byId = tJuanKnowledgeMapper.selectById(key);
            String maxCode = new String();
            if (null == questionMax) {
//                questionMax.setQuestionCode(byId.getKnowledgeCode() + "0001");
                maxCode = byId.getKnowledgeCode() + "0001";
            } else {
                maxCode = questionMax.getQuestionCode();
            }
            List<TJuanQuestion> tJuanQuestions = listMap.get(key);
            int i = 0;
            for (TJuanQuestion qs : tJuanQuestions) {
                i = i + 1;
                String questionCode = new String();
                String substring = maxCode.substring(maxCode.length() - 4);
                String format = String.format("%04d", Integer.parseInt(substring) + i);
                questionCode = byId.getKnowledgeCode() + format;
                qs.setQuestionCode(questionCode);
            }
            questionList.addAll(tJuanQuestions);
        }

        baseMapper.insertBatch(result);
    }

    @Override
    public R<Void> addQuestion(InsertQuestion bo) {
//        if (StringUtils.isBlank(bo.getCourseId())) {
//            return R.fail("请选择一门课程");
//        }
//        if (StringUtils.isBlank(bo.getReposId())) {
//            return R.fail("请选择一个题库");
//        }
        //编码校验唯一
//        LambdaQueryWrapper<TJuanQuestion> lqw = Wrappers.lambdaQuery();
//        TJuanQuestion old = baseMapper.selectOne(lqw.eq(TJuanQuestion::getQuestionCode, bo.getQuestionCode()));
//        if (null != old) {
//            return R.fail("该题目编码已存在!");
//        }
        //根据课程查询专业id
        TJuanQuestion old = new TJuanQuestion();
        BeanUtils.copyProperties(bo, old);
        //通过知识点id查询章节id
        TJuanKnowledge juanKnowledge = tJuanKnowledgeMapper.selectById(bo.getKnowledgeId());
        TJuanChapter juanChapter = tJuanChapterMapper.selectById(juanKnowledge.getChapterId());
        if (null != juanChapter) {
            old.setChapterId(juanChapter.getChapterId());
        }
        old.setCreatedTime(new Date());
        //生成编码
        String questionCode = new String();
        LambdaQueryWrapper<TJuanQuestion> questionWrapper = new LambdaQueryWrapper<>();
        questionWrapper.eq(TJuanQuestion::getKnowledgeId, bo.getKnowledgeId())
                .orderByDesc(TJuanQuestion::getQuestionCode)
                .last("LIMIT 1");
        TJuanQuestion questionMax = baseMapper.selectOne(questionWrapper);
        if (null == questionMax) {
            questionCode = juanKnowledge.getKnowledgeCode() + "0001";
        } else {
            String substring = questionMax.getQuestionCode().substring(questionMax.getQuestionCode().length() - 4);
            String format = String.format("%04d", Integer.parseInt(substring) + 1);
            questionCode = juanKnowledge.getKnowledgeCode() + format;
        }
        old.setQuestionCode(questionCode);
        int flag = baseMapper.insert(old);
        if (flag > 0) {
            //添加题目和题库的关联关系
//            TJuanReposRelated ro = new TJuanReposRelated();
//            ro.setQuestionId(old.getQuestionId());
//            ro.setReposId(bo.getReposId());
//            tJuanReposRelatedMapper.insert(ro);
            return R.ok("添加题目成功!");
        }
        return R.fail("添加题目失败!");
    }

    @Override
    public R<Void> editQuestion(TJuanQuestionBo bo) {
        if (StringUtils.isBlank(bo.getQuestionCode())) {
            return R.fail("题目编码不能为空");
        }
        TJuanQuestion old = baseMapper.selectById(bo.getQuestionId());
        if (!bo.getQuestionCode().equals(old.getQuestionCode())) {
            //code不一样，则查询code是否已经存在
            LambdaQueryWrapper<TJuanQuestion> lqw = Wrappers.lambdaQuery();
            TJuanQuestion ol = baseMapper.selectOne(lqw.eq(TJuanQuestion::getQuestionCode, bo.getQuestionCode()));
            if (null != ol) {
                return R.fail("该提醒编码已经存在!");
            }
        }
        TJuanQuestion update = new TJuanQuestion();
        BeanUtils.copyProperties(bo, update);
        baseMapper.updateById(update);
        return R.ok("更新题目成功!");
    }

    @Override
    public void exportJson(JuanQuestionDto bo, HttpServletResponse rep) throws UnsupportedEncodingException {
        LambdaQueryWrapper<TJuanQuestion> tq = Wrappers.lambdaQuery();
        LambdaQueryWrapper<TJuanChapter> tc = Wrappers.lambdaQuery();
        LambdaQueryWrapper<TJuanKnowledge> tk = Wrappers.lambdaQuery();
        //题库题目列表
        List<TJuanQuestion> questionList = baseMapper.selectList(tq.eq(TJuanQuestion::getCourseId, bo.getCourseId()));
        //课程
        TJuanCourse tJuanCourse = tJuanCourseMapper.selectById(bo.getCourseId());
        //章节
        List<TJuanChapter> tJuanChapters = tJuanChapterMapper.selectList(tc.eq(TJuanChapter::getCourseId, bo.getCourseId()));
        //知识点
        List<TJuanKnowledge> tJuanKnowledges = tJuanKnowledgeMapper.selectByCourseId(bo.getCourseId());
        ReposImportVO result = new ReposImportVO();
        result.setQuestionList(questionList);
        result.setTJuanCourse(tJuanCourse);
        result.setTJuanChapterList(tJuanChapters);
        result.setTJuanKnowledgeList(tJuanKnowledges);
        Gson gson = new Gson();
        String json = gson.toJson(result);
        rep.setContentType("application/octet-stream");
        rep.setHeader("Content-disposition", "attachment;filename=file.json");
        try {
            rep.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean importJson(MultipartFile file) {
        boolean flag = false;
        Gson gson = new Gson();
        try {
            InputStream inputStream = file.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            ReposImportVO fromJson = gson.fromJson(reader, ReposImportVO.class);
            TJuanCourse tJuanCourse = fromJson.getTJuanCourse();
            List<TJuanChapter> tJuanChapterList = fromJson.getTJuanChapterList();
            List<TJuanKnowledge> tJuanKnowledgeList = fromJson.getTJuanKnowledgeList();
            List<TJuanQuestion> questionList = fromJson.getQuestionList();
            //题库插入或更新
            tJuanCourseMapper.insertOrUpdate(tJuanCourse);
            //章节知识点插入或更新
            tJuanChapterMapper.insertOrUpdateBatch(tJuanChapterList);
            tJuanKnowledgeMapper.insertOrUpdateBatch(tJuanKnowledgeList);
            //题目插入或更新
            flag = baseMapper.insertOrUpdateBatch(questionList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (flag) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<KnowledgeReturnVO> statisticsByKnowledge(String courseId) {
        List<KnowledgeReturnVO> list = baseMapper.statisticsByKnowledge(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        Integer score = baseMapper.selectAllScore(courseId);
        if (allQuestion != 0) {
            for (KnowledgeReturnVO item : list) {
                item.setRate((float) item.getQuestionNum() / (float) allQuestion);
                item.setScoreRate((float) item.getScore() / (float) score);
            }
        }
        return list;
    }

    @Override
    public List<KnowledgeReturnVO> getStatisticsByPoint(String courseId) {
        List<KnowledgeReturnVO> list = baseMapper.getStatisticsByPoint(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        Integer score = baseMapper.selectAllScore(courseId);
        if (allQuestion != 0) {
            for (KnowledgeReturnVO item : list) {
                item.setRate((float) item.getQuestionNum() / (float) allQuestion);
                item.setScoreRate((float) item.getScore() / (float) score);
            }
        }
        return list;
    }

    /**
     * 题库-按题型统计
     *
     * @param courseId
     * @return
     */
    @Override
    public List<StatisticsByTypeVO> getStatisticsByType(String courseId, String type) {
        List<StatisticsByTypeVO> list = baseMapper.getStatisticsByType(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        Integer score = baseMapper.selectAllScore(courseId);
        String dictType = "topic_type";
        List<SysDictData> dictList = baseMapper.selectDict(dictType);
        Map<String, String> collect = dictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (StatisticsByTypeVO item : list) {
            if (allQuestion != 0) {
                item.setRate((float) item.getQuestionNum() / (float) allQuestion);
                item.setScoreRate((float) item.getScore() / (float) score);
            }
            item.setLabel(collect.get(item.getLabel()));
        }
        return list;
    }

    /**
     * 题库-按能力层次统计
     *
     * @param courseId
     * @return
     */
    @Override
    public List<StatisticsByTypeVO> getStatisticsByLevel(String courseId, String type) {
        List<StatisticsByTypeVO> list = baseMapper.getStatisticsByLevel(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        Integer score = baseMapper.selectAllScore(courseId);
        String dictType = "capability_level";
        List<SysDictData> dictList = baseMapper.selectDict(dictType);
        Map<String, String> collect = dictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (StatisticsByTypeVO item : list) {
            if (allQuestion != 0) {
                item.setRate((float) item.getQuestionNum() / (float) allQuestion);
                item.setScoreRate((float) item.getScore() / (float) score);
            }
            item.setLabel(collect.get(item.getLabel()));
        }
        return list;
    }

    /**
     * 题库-按难易度统计
     *
     * @param courseId
     * @return
     */
    @Override
    public List<StatisticsByTypeVO> getStatisticsByEasy(String courseId, String type) {
        List<StatisticsByTypeVO> list = baseMapper.getStatisticsByEasy(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        Integer score = baseMapper.selectAllScore(courseId);
        String dictType = "difficulty";
        List<SysDictData> dictList = baseMapper.selectDict(dictType);
        Map<String, String> collect = dictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (StatisticsByTypeVO item : list) {
            if (allQuestion != 0) {
                item.setRate((float) item.getQuestionNum() / (float) allQuestion);
                item.setScoreRate((float) item.getScore() / (float) score);
            }
            item.setLabel(collect.get(item.getLabel()));
        }
        return list;
    }

    /**
     * 题库-按重要性统计
     *
     * @param courseId
     * @param type
     * @return
     */
    @Override
    public List<StatisticsByTypeVO> getStatisticsByImportance(String courseId, String type) {
        List<StatisticsByTypeVO> list = baseMapper.getStatisticsByImportance(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        Integer score = baseMapper.selectAllScore(courseId);
        String dictType = "grade";
        List<SysDictData> dictList = baseMapper.selectDict(dictType);
        Map<String, String> collect = dictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (StatisticsByTypeVO item : list) {
            if (allQuestion != 0) {
                item.setRate((float) item.getQuestionNum() / (float) allQuestion);
                item.setScoreRate((float) item.getScore() / (float) score);
            }
            item.setLabel(collect.get(item.getLabel()));
        }
        return list;
    }

    @Override
    public QuestionVO getStatisticsByRelevance(String courseId) {
        QuestionVO result = new QuestionVO();
        List<TJuanQuestion> relevances = baseMapper.getStatisticsByRelevance(courseId);
        Integer allQuestion = baseMapper.selectAllQuestion(courseId);
        result.setQuestionList(relevances);
        if (allQuestion != 0) {
            result.setRate((float) relevances.size() / (float) allQuestion);
        }
        return result;
    }
}
